import axios from "axios";
import { getToken, removerUserInfo } from ".";
import { Toast } from "antd-mobile";
import { createBrowserHistory } from "umi";
const history = createBrowserHistory();
axios.defaults.timeout = 8000;
axios.defaults.baseURL = process.env.NODE_ENV === 'development'? '/conner': 'https://api.it120.cc/conner';
axios.defaults.headers['content-type'] = 'application/x-www-form-urlencoded';


// 添加拦截器
axios.interceptors.request.use((config) => {
  if (getToken()) {
    if (config.method === 'get' || config.method === 'delete') {
      config.params = {
        ...config.params,
        token: getToken()
      }
    } else {
      config.data = {
        ...config.data,
        token: getToken()
      }
    }
  }
  return config
}, (err) => {
  return Promise.reject(err)
})

// 添加响应拦截器
axios.interceptors.response.use((res) => {
  if (res.data.code === 2000) {
    // 清除用户缓存， 弹出错误提示 跳转到登录页
    removerUserInfo()
    Toast.show({
      icon: 'fail',
      content:'用户登录状态过期或未登录',
      afterClose: () => {
        // 去登录页
        history.replace('/login');
        history.go(0);
      }
    })
  }
  return res
}, (err) => {
  return Promise.reject(err)
})

export default axios